/**
 * XAce - layui 图标选择器
 *
 * 基于iconHhysFa 1.0改造，包含font-awesome图标和layui的图标
 * @modify imlzw  adai.imlzw.cn imlzw@vip.qq.com
 * @Date 2020-10-27
 * @version 1.0.1
 * 1.0 改造内容：
 * - 采用fixed下拉模式，自动识别上下下拉方向，识别弹出，
 * - 支持zIndex定义，避免下拉被遮挡的问题
 * - 支持同时选择layui icon 与 font-awesome图标选择
 * - 优化冗余代码, 精简配置
 * - 修改下拉样式，采用紧凑风格，所有图标尽收眼底
 *
 * @config 配置参数
 *
 * {
        // 选择器，推荐使用input
        id: 'demo1',
        // xAce组件目录路径，用于加载其它相关文件
        base: './xAce/',
        theme: 'monokai',
        lang: 'text',
 * }
 *
 */

layui.define(['jquery', 'layer'], function (exports) {
    "use strict";

    let $ = layui.jquery;
    let resources = [];

    let XAce = function () {
        this.v = '1.0';
        this.renderIns = {};
    };

    /**
     * 渲染组件
     */
    XAce.prototype.render = function (options) {
        let base = layui.cache.modules.xAce.replace("xAce.js", "") || '';
        let that = this;
        let promise = new Promise((resolve, reject) => {
            that.loadCss(base + "xAce.css", function () {
                that.loadJS(base + "ace/ace.js", function () {
                    let editor = ace.edit(options.id);
                    editor.setValue(options.initValue || '');
                    that.renderIns[options.id] = editor;
                    editor.setTheme("ace/theme/" + (options.theme || 'monokai'));
                    editor.session.setMode("ace/mode/" + (options.lang || 'text'));
                    if (options.commands) {
                        options.commands.forEach(function (command) {
                            editor.commands.addCommand(command);
                        });
                    }
                    resolve(editor);
                });
            })
        });
        return promise;
    }
    /**
     * 动态加载js文件
     * @param url
     * @param callback
     */
    XAce.prototype.loadJS = function (url, callback) {
        if (this.isLoaded(url)) {
            callback && callback();
            return;
        }
        var script = document.createElement('script'),
            fn = callback || function () {
            };
        script.type = 'text/javascript';
        //IE
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == 'loaded' || script.readyState == 'complete') {
                    resources.push(url);
                    script.onreadystatechange = null;
                    fn();
                }
            };
        } else {
            //其他浏览器
            script.onload = function () {
                resources.push(url);
                fn();
            };
        }
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    /**
     * 加载css文件
     * @param url
     */
    XAce.prototype.loadCss = function (url, callback) {
        if (!url || url.length === 0) {
            throw new Error('argument "url" is required !');
        }
        if (this.isLoaded(url)) {
            callback && callback();
            return;
        }
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = url;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.onload = function () {
            resources.push(url);
            if (callback != null) {
                callback();
            }
        };
        head.appendChild(link);
    }

    /**
     * 判断是否加载过资源了
     * @param url
     * @returns {boolean}
     */
    XAce.prototype.isLoaded = function (url) {
        if (url) {
            for (let urlResource of resources) {
                if (url == urlResource) {
                    return true;
                }

            }
        }
        return false;
    }
    var xAce = new XAce();
    exports("xAce", xAce);
});